package com.wujunshen.dumpling.core.engine.freemark;

import com.wujunshen.dumpling.common.constant.Constants;
import com.wujunshen.dumpling.common.utils.Assert;
import com.wujunshen.dumpling.common.utils.FileUtils;
import com.wujunshen.dumpling.core.engine.AbstractTemplateEngine;
import com.wujunshen.dumpling.core.engine.EngineConfig;
import com.wujunshen.dumpling.database.metadata.model.Data;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.*;
import java.util.Locale;
import java.util.Objects;

import static com.wujunshen.dumpling.core.engine.EngineTemplateType.FREEMARKER;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * freemarker template produce
 *
 * @author frankwoo
 */
@Slf4j
@EqualsAndHashCode(callSuper = false)
public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
  /** freemarker 配置实例化 */
  private final Configuration configuration =
      new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

  {
    try {
      String path = getEngineConfig().getCustomTemplate();
      // 自定义模板
      if (StringUtils.isNotBlank(path) && FileUtils.isFileExists(path)) {
        // 获取父目录
        String parent = Objects.requireNonNull(FileUtils.getFileByPath(path)).getParent();
        // 设置模板加载路径
        configuration.setDirectoryForTemplateLoading(new File(parent));
      }
      // 加载自带模板
      else {
        // 模板存放路径
        configuration.setTemplateLoader(
            new ClassTemplateLoader(this.getClass(), FREEMARKER.getTemplateDir()));
      }
      // 编码
      configuration.setDefaultEncoding(Constants.DEFAULT_ENCODING);
      // 国际化
      configuration.setLocale(new Locale(Constants.DEFAULT_LOCALE));
    } catch (Exception e) {
      log.error("exception message is:{}", ExceptionUtils.getStackTrace(e));
    }
  }

  public FreemarkerTemplateEngine(EngineConfig templateConfig) {
    super(templateConfig);
  }

  /**
   * 生成文档
   *
   * @param data {@link Data}
   */
  @SneakyThrows
  @Override
  public void produce(Data data, String docName) {
    Assert.isNotNull(data);
    String path = getEngineConfig().getCustomTemplate();
    Template template;
    // freemarker template
    // 如果自定义路径不为空,文件也存在
    if (StringUtils.isNotBlank(path) && FileUtils.isFileExists(path)) {
      // 文件名称
      String fileName = new File(path).getName();
      template = configuration.getTemplate(fileName);
    } else {
      // 获取系统默认的模板
      template =
          configuration.getTemplate(
              getEngineConfig().getFileType().getTemplateNamePrefix() + FREEMARKER.getSuffix());
    }
    // create file
    File file = getFile(docName);
    // writer freemarker
    try (Writer out =
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8))) {
      // process
      template.process(data, out);
      // open the output directory
      openOutputDir();
    }
  }
}
